<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\RoleAccessRepo;
use App\Repositories\RoleRepo;
use App\Models\Role;
class RoleController extends BaseController
{
    protected $roleRepo;

    public function  _initialize()
    {
        $this->roleRepo = new RoleRepo;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    public function all()
    {
        $data =  $this->roleRepo->getAll();

        foreach ($data as &$item) {
            if(!empty($item['access'])) {
                $item['access_ids'] = array_column($item['access'], 'access_id');
            } 
            if(!empty($item['menus'])) {
                $item['menu_ids'] = array_column($item['menus'], 'menu_id');
            } 
        }
        return $this->sucRes(200,$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
       $data['name'] = $request->input('name');
       $this->roleRepo->createRole($data);
       return $this->sucRes();
    }
    public function update(Request $request)
    {
       $id =   $request->id;
       $data['name'] = $request->input('name');
       $this->roleRepo->updateRole($id,$data);
       return $this->sucRes();
    }
    /**
     * 给角色赋权限
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function updatePermission(Request $request)
    {
      $role_id = $request->input('role_id');
      $access_ids = $request->input('access_ids');
      $roleAccessRepo = new RoleAccessRepo;
      $roleAccessRepo->givePromiss($role_id,$access_ids);

      return $this->sucRes();      
    }
    public function updateMenu(Request $request)
    {
      $role_id = $request->input('role_id');
      $menu_ids = $request->input('menu_ids');
      $this->roleRepo->saveMenus($role_id,$menu_ids);
      return $this->sucRes();      
    }
}
